import java.sql.*;
import java.util.*;

//This program does sorting based on key as well as value without using comparator 

public class JdbcCollAss 
{
	public static void main(String[] args) 
	{
		DBAPI obj= new DBAPI();
		
		ResultSet rs = obj.dbQuery("Select * from student;");
		
		Map <Integer, StudentDetails> hm = new LinkedHashMap <Integer, StudentDetails>();
	
		try
		{
			while (rs.next ())
			{
				int idVal = rs.getInt ("id");
				String nameVal = rs.getString (2);
				String catVal = rs.getString ("email");
				hm.put(idVal, new StudentDetails(nameVal, catVal));
				
				System.out.println (
	    			"id = " + idVal
	    			+ ", name = " + nameVal
	    			+ ", email = " + catVal);
			}
			rs.close ();
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		System.out.println("****************End of reading from database********");
//*************** Sorting based on key value******************************
		Map <Integer, StudentDetails> tm = new TreeMap <Integer, StudentDetails>(hm);
		// Get a set of the entries 
		Set set1 = tm.entrySet();
				
		// Get an iterator 
		Iterator i = set1.iterator();
		StudentDetails temp;

		Map <String, Integer> tm1 = new TreeMap <String, Integer>();
		// Display elements 
		while(i.hasNext()) 
		{
			Map.Entry <Integer, StudentDetails>me = (Map.Entry)i.next(); 
			System.out.print(me.getKey() + ": ");
			temp = (StudentDetails)me.getValue();
			System.out.print(temp.name+" ");
			tm1.put(temp.name, me.getKey());
			System.out.println(temp.emailid);
		} 
		System.out.println("*********End of Sorting based on Key value******");
//************ Sorting based on name***************************************
		Map <Integer, StudentDetails>sortValue = new LinkedHashMap <Integer, StudentDetails>();
				
		// Get a set of the entries 
		Set s1 = tm1.entrySet();
						
		// Get an iterator 
		Iterator i1 = s1.iterator();
		Integer key;

		// Display elements 
		while(i1.hasNext()) 
		{
			Map.Entry <String,Integer>me = (Map.Entry) i1.next(); 
			System.out.print(me.getKey() + ": ");
			key = me.getValue();
			sortValue.put(key,tm.get(key));
			System.out.println(key);
		} 
		// Get a set of the entries 
		Set set2 = sortValue.entrySet();
		StudentDetails temp1;
		
		// Get an iterator 
		Iterator i2 = set2.iterator();
		// Display elements 
		while(i2.hasNext()) 
		{
			Map.Entry <Integer, StudentDetails>me = (Map.Entry) i2.next(); 
			System.out.print(me.getKey() + ": ");
			temp1 = (StudentDetails)me.getValue();
			System.out.print(temp1.name+" ");
			//hm1.put(temp.name, me.getKey());
			System.out.println(temp1.emailid);
		} 
	}
}
